package cn.gjxblog.modules.job.utils;

import cn.gjxblog.common.utils.spring.SpringContextUtils;
import cn.gjxblog.modules.job.constant.JobConstant;
import cn.gjxblog.modules.job.entity.ScheduleJobEntity;
import cn.gjxblog.modules.job.entity.ScheduleJobLogEntity;
import cn.gjxblog.modules.job.service.ScheduleJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 定时任务
 * @Author guojiaxun
 * @Date 2019/9/18 14:00
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().get(JobConstant.JOB_PARAM_KEY);

        //获取
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");

        //数据库保存执行记录
        ScheduleJobLogEntity entity = new ScheduleJobLogEntity();
        entity.setJobId(scheduleJob.getJobId());
        entity.setBeanName(scheduleJob.getBeanName());
        entity.setParams(scheduleJob.getParams());
        entity.setCreateTime(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.debug("任务准备执行，任务ID：" + scheduleJob.getJobId());

            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);

            method.invoke(target, scheduleJob.getParams());

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            entity.setTimes((int)times);
            //任务状态    0：成功    1：失败
            entity.setStatus(0);

        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            entity.setTimes((int)times);

            //任务状态    0：成功    1：失败
            entity.setStatus(1);
            entity.setError(StringUtils.substring(e.toString(), 0, 2000));
        }finally {
            scheduleJobLogService.save(entity);
        }


    }
}
